package com.clouddong.exterapi.service.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.clouddong.exterapi.ProbeConstant;
import com.clouddong.exterapi.dao.ProbeListDaoI;
import com.clouddong.exterapi.dao.ProbeTaskDaoI;
import com.clouddong.exterapi.po.ProbeListTablePo;
import com.clouddong.exterapi.service.ProbeTaskServiceI;
import com.clouddong.exterapi.util.HttpClientUtil;
import com.clouddong.exterapi.util.JsonPluginsUtil;
import com.clouddong.exterapi.vo.DnsVo;
import com.clouddong.exterapi.vo.PingVo;
import com.clouddong.exterapi.vo.ProbeListTableVo;
import com.clouddong.exterapi.vo.ProbeTaskAddVo;
import com.clouddong.exterapi.vo.ProbeTaskDelVo;
import com.clouddong.exterapi.vo.ProbeTaskTableVo;
import com.clouddong.exterapi.vo.ProbeXmlPingVo;
import com.clouddong.exterapi.vo.ProbeXmlVo;
import com.clouddong.exterapi.vo.TraceVo;
import com.clouddong.exterapi.websocket.MyClient;

import ainx.common.util.DateUtil;
@Service("probeTaskAddService")
@PropertySource("classpath:params.properties")
@PropertySource("classpath:probe_config.properties")
public class ProbeTaskServiceImpl implements ProbeTaskServiceI{


	@Autowired
	private Environment env;
    @Autowired
    private ProbeTaskDaoI pAddDaoI;
    @Autowired
    private ProbeListDaoI probeListDaoI;

    private final static Logger logger=LoggerFactory.getLogger(ProbeTaskServiceImpl.class);
   private String getProbeTaskId(ProbeTaskTableVo probeTaskTableVo){
        pAddDaoI.getProbeTaskId(probeTaskTableVo);
        String taskid=probeTaskTableVo.getId().toString();
        //System.out.println(probeTaskTableVo.getId());
        return taskid;
    }
   private String insTaskInfo(String taskid, Map<String, String> retMap,String type){

            ProbeTaskTableVo probetask=new ProbeTaskTableVo();
            probetask.setTaskid(taskid);
            probetask.setType(type);
            String command = retMap.get("command");
            String retmsg = retMap.get("retmsg");
            probetask.setCommand(command);
            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dfdate=df.format(new Date());
            probetask.setCreatetime(dfdate);
            JSONObject jsonObject=new JSONObject();
            jsonObject=JSONObject.parseObject(retmsg);
            String retcode="";
            if(retmsg!=null){
            	retcode=jsonObject.get("status_code").toString();
            }
            probetask.setRet_code(retcode);
            probetask.setRet_msg(retmsg);
            //更新数据表
            pAddDaoI.insTaskInfo(probetask);
            String taskinfologid=probetask.getId().toString();
            System.out.println(probetask.getId());
            return taskinfologid;
    }
    private Map<String, String> taskSend(List<Object> listObject,String url){
        
        //重新组织json串发送探针侧
        String returnString="";
        String listinput=JsonPluginsUtil.beanToJson(listObject).toString();
        System.out.println(listinput);
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("data",listinput);
        //获取返回的消息存入更新数据表
        returnString=HttpClientUtil.doPost(url, map, "UTF-8");
        String command=map.toString();
        String retmsg=returnString;
        Map<String, String> retMap=new HashMap<String, String>();
        retMap.put("command", command);
        retMap.put("retmsg", retmsg);
        //返回消息
        return retMap;
    }
    private String getTaskId(){
      //插入数据表返回id
        ProbeTaskTableVo probetask=new ProbeTaskTableVo();
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dfdate=df.format(new Date());
        probetask.setCreatetime(dfdate);
        String taskid=getProbeTaskId(probetask);
 
        return taskid;
    }
    private ProbeTaskAddVo taskJsonData(String taskid,String tasktypeid,String destaddr,String proids,String rule){
    	ProbeListServiceImpl probeListServiceImpl=new ProbeListServiceImpl();
    	List<String> probeids=new ArrayList<String>();
    	//获取探针列表
		if((proids==null)||(proids.equals(""))){
			//全网
			ProbeListTableVo proListTableVo=new ProbeListTableVo();
            List probeListTablePos = getProbeDataList(proListTableVo);
			for (int i = 0; i < probeListTablePos.size(); i++) {
                probeids.add(((ProbeListTablePo)probeListTablePos.get(i)).getProbe_id());
			}
			
		}else{
	        //部分
	        int num=proids.split(",").length;
	        String[] ps=proids.split(",");
	        for (int i = 0; i < num; i++) {
	        	String proid=ps[i];
	        	probeids.add(proid);
			};
		}
		String url=env.getProperty("probeaddreturl");
		ProbeTaskAddVo probetaskjson=new ProbeTaskAddVo();
		switch(tasktypeid) {
			//PING测试--封堵方式
			case "0":
				probetaskjson= getJsonPing(url,taskid, tasktypeid, destaddr, rule, probeids);
				break;
			//PING测试--PING方式
			case ProbeConstant.TYPE_ID_PING:
				probetaskjson = getJsonPing(url,taskid, tasktypeid, destaddr, rule, probeids);
				break;
			//HTTP测试
			case ProbeConstant.TYPE_ID_HTTP:
				//probetaskjson = getJsonPing(url,taskid, tasktypeid, destaddr, rule, probeids);
				break;
			//FLASH测试
			case ProbeConstant.TYPE_ID_FLASH:
				//probetaskjson = getJsonPing(url,taskid, tasktypeid, destaddr, rule, probeids);
				break;
			//DNS测试
			case ProbeConstant.TYPE_ID_DNS:
				probetaskjson = getJsonDNS( url,taskid, tasktypeid, destaddr, rule, probeids);
				break;
			//Trace测试
			case ProbeConstant.TYPE_ID_TRACE:
				probetaskjson = getJsonTrace(url,taskid, tasktypeid, destaddr, rule, probeids);
				break;


		}

		//listObject.add(probedns);

		return probetaskjson;

    }

	private ProbeTaskAddVo getJsonTrace(String url,String taskid, String tasktypeid, String destaddr, String rule, List<String> probeids) {
		//增加trace的json
		ProbeTaskAddVo probetrace=new ProbeTaskAddVo();
		probetrace.setSource_id(env.getProperty("source_id"));
		probetrace.setUrl(url);
		probetrace.setTask_type_id(tasktypeid);
		probetrace.setTask_id(taskid);
		probetrace.setDest_addr(destaddr);
		probetrace.setProbe_id(probeids);
		probetrace.setTest_slot_rule(rule);
		TraceVo traceVo=new TraceVo();
		traceVo.setMax_invalid_hops(env.getProperty("max_invalid_hops_trace"));
		traceVo.setPkt_count(env.getProperty("pkt_count_trace"));
		traceVo.setPkt_interval(env.getProperty("pkt_interval_trace"));
		traceVo.setPkt_size(env.getProperty("pkt_size_trace"));
		probetrace.setTask_param(traceVo);

		return probetrace;
	}

	private ProbeTaskAddVo getJsonDNS(String url,String taskid, String tasktypeid, String destaddr, String rule, List<String> probeids) {
		//增加dns的json

		ProbeTaskAddVo probedns=new ProbeTaskAddVo();
		probedns.setUrl(url);
		probedns.setTask_type_id(tasktypeid);
		probedns.setTask_id(taskid);
		probedns.setDest_addr(destaddr);
		probedns.setProbe_id(probeids);
		probedns.setTest_slot_rule(rule);
		DnsVo dnsVo=new DnsVo();
		dnsVo.setDns_domain(destaddr);
		dnsVo.setPkt_count(env.getProperty("pkt_count_dns"));
		dnsVo.setPkt_interval(env.getProperty("pkt_interval_dns"));
		probedns.setTask_param(dnsVo);
		return probedns;
	}

	private ProbeTaskAddVo getJsonPing(String url,String taskid, String tasktypeid, String destaddr, String rule, List<String> probeids) {
		//组织任务增加的json串
		ProbeTaskAddVo probeping=new ProbeTaskAddVo();
		//ResourceBundle rb = ResourceBundle.getBundle("params");
		//String url=rb.getString("probeaddreturl");
		if(rule==null||"0".equals(rule))
		{
		    probeping.setSource_id(env.getProperty("source_id2"));
		}else {
		    probeping.setSource_id(env.getProperty("source_id"));
        }
		//probeping.setSource_id(env.getProperty("source_id"));
		probeping.setUrl(url);
		probeping.setTask_type_id(tasktypeid);
		probeping.setTask_id(taskid);
		probeping.setDest_addr(destaddr);
		probeping.setProbe_id(probeids);
		probeping.setTest_slot_rule(rule);
		PingVo pingVo=new PingVo();
		probeping.setTask_param(pingVo);
		pingVo.setPkt_count(env.getProperty("pkt_count_ping"));
		pingVo.setPkt_interval(env.getProperty("pkt_interval_ping"));
		pingVo.setPkt_size(env.getProperty("pkt_size_ping"));
		return probeping;
	}

	private List getProbeDataList(ProbeListTableVo proListTableVo)
    {
        logger.info("vo输入打印2：" + JsonPluginsUtil.toPrintString(proListTableVo));
        List probeListTablePos = probeListDaoI.getProbeListByparams(proListTableVo);
        return probeListTablePos;
    }

    private ProbeTaskDelVo taskDelJsonData(String taskids){
        
        List<String> taskidsl=new ArrayList<String>();
        int num=taskids.split(",").length;
        String[] ts=taskids.split(",");
        for (int i = 0; i < num; i++) {
        	String taskid=ts[i];
        	taskidsl.add(taskid);
		};

        ProbeTaskDelVo pDelVo=new ProbeTaskDelVo();
        pDelVo.setTask_id(taskidsl);
		pDelVo.setSource_id(env.getProperty("source_id"));
    	//ResourceBundle rb = ResourceBundle.getBundle("params");
        //String url=rb.getString("probedelreturl");
		String url=env.getProperty("probedelreturl");
        pDelVo.setUrl(url);
        return pDelVo;
    }

	/* (non-Javadoc)
	 * @see com.clouddong.exterapi.service.ProbeTaskServiceI#probeAdd(java.lang.String)
	 */
	@Override
	public Map<String, String> probeAdd(String tasktypeid, String destaddr, String proids, String rule) {
		//默认5分钟频次
	    //默认手动频次	    
		rule=rule==null?"0":rule;
		//获得测试类型的编码
		String typeId=getTypeId(tasktypeid);
		//获取taskid
        String taskid=getTaskId();
        //组织发送的测试数据
        ProbeTaskAddVo pTaskAddVo=taskJsonData(taskid,typeId,destaddr,proids,rule);
        List<Object> listObject=new ArrayList<Object>();
        listObject.add(pTaskAddVo);
        System.out.println(listObject);
        
       //发送探针侧
        //String url="http://61.149.4.232:9099/dataproxy/proxy/task/v2/add";
    	//ResourceBundle rb = ResourceBundle.getBundle("params");
        //String url=rb.getString("probeaddurl");
		String url=env.getProperty("probeaddurl");
        Map<String, String> retMessageMap=taskSend(listObject,url);
        //下发策略后插入业务数据表
        insTaskInfo(taskid, retMessageMap,"add");
		String retcode=getRetMsg(retMessageMap,"status_code");
		String isNotSucc=retcode.equals("0")?"success":"error";
		Map<String,String> retmap=new HashMap<String,String>();
		retmap.put("msg",isNotSucc);
		retmap.put("taskid",taskid);
		//probeXmlReader("D://workSpace2018//CloudDongInterface//target//CloudDunInterface//upload//20180802112025-0.xml");
		return retmap;
	}

	private String getRetMsg(Map<String, String> retMap,String key) {
		JSONObject jsonObject=new JSONObject();
		String retmsg = retMap.get("retmsg");
		jsonObject=JSONObject.parseObject(retmsg);
		String retcode="";
		if(retmsg!=null){
			retcode=jsonObject.get(key).toString();
		}
		return retcode;
	}

	private String getTypeId(String tasktypeid) {
		//组织测试方式的字典
		//测试类型编号 0--封堵方式(实质上也是ping方式，只是区分开展示颜色),1--ping,2--http,3--flash,4--dns,5--trace
		Map<String,String> typeMap=new HashMap<String,String>();
		//ping方式
		typeMap.put("0", ProbeConstant.TYPE_ID_PING);
		typeMap.put("1",ProbeConstant.TYPE_ID_PING);
		typeMap.put("2",ProbeConstant.TYPE_ID_HTTP);
		typeMap.put("3",ProbeConstant.TYPE_ID_FLASH);
		typeMap.put("4",ProbeConstant.TYPE_ID_DNS);
		typeMap.put("5",ProbeConstant.TYPE_ID_TRACE);
		String typeid=typeMap.get(tasktypeid);
		return typeid;
	}

	/* (non-Javadoc)
	 * @see com.clouddong.exterapi.service.ProbeTaskServiceI#probeDel(java.lang.String, java.lang.String)
	 */
	@Override
	public Map probeDel(String taskids) {
		//组织发送的测试数据
        ProbeTaskDelVo pTaskDelVo=taskDelJsonData(taskids);
        List<Object> listObject=new ArrayList<Object>();
        listObject.add(pTaskDelVo);
        
		String sendurl=env.getProperty("probedelurl");
        Map<String, String> retMessageMap=taskSend(listObject,sendurl);
		int num=taskids.split(",").length;
        String[] ts=taskids.split(",");
		String retcode=getRetMsg(retMessageMap,"status_code");
		Map<String,String> retmap=new HashMap<String,String>();
		if(retcode.equals("0")) {
			for (int i = 0; i < num; i++) {
				String taskid = ts[i];
				//删除任务插入业务数据表
				insTaskInfo(taskid, retMessageMap, "del");
				upTaskTable(taskid);
			}
			String description=getRetMsg(retMessageMap,"description");
			retmap.put("msg","success");
			retmap.put("description",description);
			return retmap;
		}else{
			for (int i = 0; i < num; i++) {
				String taskid = ts[i];
				//删除任务插入业务数据表
				insTaskInfo(taskid, retMessageMap, "del");
				//upTaskTable(taskid);
			}
			String description=getRetMsg(retMessageMap,"description");
			retmap.put("msg","error");
			retmap.put("description",description);
			return retmap;

		}
	}
    private void upTaskTable(String taskid){
        ProbeTaskTableVo probeTaskTableVo = new ProbeTaskTableVo();
        probeTaskTableVo.setId(Long.valueOf(taskid));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dfdate = df.format(new Date());
        probeTaskTableVo.setEndtime(dfdate);
        pAddDaoI.upTaskTable(probeTaskTableVo);
    };
	
	/**
     * 返回响应
     * 
     * @throws Exception
     */
    private void sendResponse(String responseString) throws Exception {
//     response.setContentType("application/json;charset=UTF-8");
//      PrintWriter pw = null;
//      try {
//        pw = response.getWriter();
//        pw.write(responseString);
//        pw.flush();
//      } finally {
//        IOUtils.closeQuietly(pw);
//      }
    }
	/* (non-Javadoc)
	 * @see com.clouddong.exterapi.service.ProbeTaskServiceI#probeData(com.clouddong.exterapi.service.HttpServletRequest, com.clouddong.exterapi.service.HttpServletResponse)
	 */
	@Override
	public void probeData(HttpServletRequest request,String uploadPath) throws Exception {
		  //定义文件名称暂存
		  String fname=null;
	      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
	      File tmpDir = new File("d:\\temp");  //初始化上传文件的临时存放目录,必须是绝对路径 
	      try {  
	          if (ServletFileUpload.isMultipartContent(request)) {  
	              DiskFileItemFactory factory = new DiskFileItemFactory();  
	            //指定在内存中缓存数据大小,单位为byte,这里设为1Mb
	              factory.setSizeThreshold(1 * 1024 * 1024); 
	            //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 
	              factory.setRepository(tmpDir);   
	              ServletFileUpload sfu = new ServletFileUpload(factory);  
	           // 指定单个上传文件的最大尺寸,单位:字节，这里设为5Mb 
	              sfu.setFileSizeMax(5 * 1024 * 1024);  
	            //指定一次上传多个文件的总尺寸,单位:字节，这里设为10Mb 
	              sfu.setSizeMax(10 * 1024 * 1024);   
	              sfu.setHeaderEncoding("UTF-8");  //设置编码
	              List<FileItem> fileItems = sfu.parseRequest(request); // 解析request请求  
	              //uploadPath = uploadPath + "upload\\";  // 选定上传的目录此处为当前目录 ==windows
	              uploadPath = uploadPath + "upload/";  // 选定上传的目录此处为当前目录  ==linux
	              if (!new File(uploadPath).isDirectory()){
	                  new File(uploadPath).mkdirs();//选定上传的目录此处为当前目录，没有则创建   
	              }  
	              int leng = fileItems.size();

	              for(int n=0;n<leng;n++) {  
	                  FileItem item = fileItems.get(n); // 从集合中获得一个文件流  
	                  // 如果是普通表单字段    
	                  if(item.isFormField()) {    
	                      String name = item.getFieldName();  // 获得该字段名称  
	                      String value = item.getString("utf-8"); //获得该字段值  
	                      System.out.println(name+value);  
	                  }else if(item.getName().length()>0) { // 如果为文件域    
	                      String iname = item.getName().substring(  
	                              item.getName().lastIndexOf("."));    
	                      fname=sdf.format(new Date())+"-"+n+iname;
	                        
	                      try {    
	                          item.write(new File(uploadPath, fname));  // 写入文件  
	                      } catch (Exception e) {    
	                          e.printStackTrace();    
	                      }  
	                  }  
	              }  
	          }
			  /**
			   * 读取解析xml文件到数据表nf_probexml及nf_probexml_*(ping,dns,trace)表
			   */
			  logger.info("####开始解析："+uploadPath+fname);
			  probeXmlReader(uploadPath+fname,request);
			  logger.info("####解析结束："+uploadPath+fname);
		  }catch (Exception e) {
	          e.printStackTrace();
			  //实现回滚，这样的话，就可以在抛异常后也能return 返回值
			  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	      }    
        
	}
	/* (non-Javadoc)
	 * @see com.clouddong.exterapi.service.ProbeTaskServiceI#probeXmlReader()
	 */
	@Override
	//**碰到什么异常都可以回滚*/
	@Transactional(rollbackFor=Exception.class)
	public void probeXmlReader(String fileUrl,HttpServletRequest request) {
		long lasting = System.currentTimeMillis();
		   logger.info(String.valueOf(lasting));
		   try {   
		     File f = new File(fileUrl);   
		     SAXReader reader = new SAXReader();   
		     Document doc = reader.read(f);   
		     Element root = doc.getRootElement(); 
		     //读取xml文件内容
		     Attribute  rootattr=root.attribute("probe_id");
		     String probe_id=rootattr.getValue();
		     Element datalist=root.element("data_list");
		     Element foo;   
		     for (Iterator i = datalist.elementIterator("data_item"); i.hasNext();) {   
		        foo = (Element) i.next(); 
		        Attribute typenameattr=foo.attribute("type_name");
		        String type_name=typenameattr.getValue();
				Attribute taskidattr=foo.attribute("task_id");
				String task_id=taskidattr.getValue();
				 /**
				  * 插入nf_probexml主表,获取xmlid
				  */
		        String xmlid = insProbeXml(probe_id, foo);

				 /**
				  * 根据类型不同存储不同的数据表
				  */
		        if(type_name.equals(ProbeConstant.TYPE_NAME_PING)){
					/**
					 * ping类型插入nf_probexml_ping表
					 */
		        	insProbeXmlPing(foo, xmlid);
		        }else if (type_name.equals(ProbeConstant.TYPE_NAME_DNS)) {
					/**
					 * dns类型插入nf_probexml_dns表
					 */


				}else if (type_name.equals(ProbeConstant.TYPE_NAME_TRACE)){
					/**
					 * trace类型插入nf_probexml_trace表
					 */
					
				}
				 /**
				  * 服务端调用webSocket给页面发送请求，告诉页面数据已落表,可以调用查询
				  */
				 runWebSocket(task_id,request);
		     }   
		    } catch (Exception e) {   
		     e.printStackTrace();
			   /**
				* 实现回滚，这样的话，就可以在抛异常后也能return 返回值
				*/
			   TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    }
		
	}
	/**
	 * @param foo
	 * @param xmlid
	 */
	private void insProbeXmlPing(Element foo, String xmlid) {
		
		try {
			String dns_delay=foo.elementText("dns_delay");
			String rtt=foo.elementText("rtt");
			String jitter=foo.elementText("jitter");
			String lost_rate=foo.elementText("lost_rate");
			String lost_pkt_count=foo.elementText("lost_pkt_count");
			String host_ip=foo.elementText("host_ip");
			String test_time=foo.elementText("test_time");
			
			ProbeXmlPingVo probeXmlPingVo=new ProbeXmlPingVo();
			probeXmlPingVo.setXml_id(Long.valueOf(xmlid));
			probeXmlPingVo.setTest_time(test_time);
			probeXmlPingVo.setRtt(rtt);
			probeXmlPingVo.setDns_delay(dns_delay);
			probeXmlPingVo.setJitter(jitter);
			probeXmlPingVo.setLost_rate(lost_rate);
			probeXmlPingVo.setLost_pkt_count(lost_pkt_count);
			probeXmlPingVo.setHost_ip(host_ip);
			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dfdate=df.format(new Date());
			probeXmlPingVo.setCreate_time(dfdate);
			pAddDaoI.insProbePingXml(probeXmlPingVo);
		} catch (Exception e) {
			logger.error("插入nf_probexml_ping表失败!",e);
			//实现回滚，这样的话，就可以在抛异常后也能return 返回值
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		
	}
	/**
	 * @param probe_id
	 * @param foo
	 * @return
	 */
	private String insProbeXml(String probe_id, Element foo) {
		try {
			//获取公共字段
			Attribute taskidattr=foo.attribute("task_id");
			Attribute typeidattr=foo.attribute("type_id");
			Attribute typenameattr=foo.attribute("type_name");
			logger.info("task_id:"+taskidattr.getValue());
			String task_id=taskidattr.getValue();
			String type_id=typeidattr.getValue();
			String type_name=typenameattr.getValue();
			String test_time=foo.elementText("test_time");
			//插入nf_probexml主表
			ProbeXmlVo probeXmlVo=new ProbeXmlVo();
			probeXmlVo.setProbe_id(probe_id);
			probeXmlVo.setTask_id(task_id);
			probeXmlVo.setTest_time(test_time);
			probeXmlVo.setType_id(type_id);
			probeXmlVo.setType_name(type_name);
			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dfdate=df.format(new Date());
			probeXmlVo.setCreate_time(dfdate);
			pAddDaoI.insProbeXml(probeXmlVo);
			String xmlid=probeXmlVo.getId().toString();
			return xmlid;
		} catch (Exception e) {
			logger.error("插入nf_probexml表失败!",e);
			//实现回滚，这样的话，就可以在抛异常后也能return 返回值
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "error";
		}
		

	}

	public void runWebSocket(String taskid,HttpServletRequest request) {
		MyClient client = new MyClient();
		logger.info("服务器："+request.getLocalAddr()+":"+request.getLocalPort());
		logger.info("客户机："+request.getRemoteAddr()+":"+request.getRemotePort());
		String addrPort=request.getLocalAddr()+":"+request.getLocalPort();
		String ContextPath=request.getContextPath();
		/**
		 * 由于现网能不能从servlet里取出ip及端口未知，保留第一和第二种方法
		 */
		//第一种方法从servlet里取ip及端口
		//String uri = "ws://"+addrPort+ContextPath+"/websocket?service"+taskid;
		//第二种方法从配置文件里取
		String websocketurl=env.getProperty("websocketurl");
		String uri=websocketurl+"service"+taskid;

		logger.info("服务端webSocketUri:"+uri);
		client.start(uri);
		try {
			client.sendMessage("success");
			client.closeSocket();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
	ProbeTaskServiceImpl probeTaskServiceImpl=new ProbeTaskServiceImpl();
	//probeTaskServiceImpl.probeXmlReader("D://workSpace2018//CloudDongInterface//target//CloudDunInterface//upload//20180802112025-0.xml");
	//String url=request.getRealPath("/");
	
	}
	@Test
	public void test()
	{
	    //String url=request.getRealPath("/");
	    String url="C://testXMl.xml";
	    System.out.println(probeTestXmlOutUrl(url));
	    //System.out.println(new Random().nextInt(2)+"");
	}
	 /**   
     <blockquote>
     <h1>生成测试用的XML</h1>
	 * @param url
     * @return 
     */
	@Override
	public Boolean probeTestXmlOutUrl(String url) {
	    Boolean retBool=false;//是否生成成功
	    try{
            Random rand = new Random();
            List<ProbeListTableVo> dataList= probeListDaoI.getProbeList();
            //获取nf_probe_list下的一个随机probe_id
	        String probeId = dataList.get(rand.nextInt(dataList.size())).getProbe_id();
	        //获取task_id
	        String taskId = (pAddDaoI.getMaxId())+"";
            // 创建一个xml文档
            Document doc = DocumentHelper.createDocument();
            // 向xml文件中添加注释
            //doc.addComment("这是根据表自动生成的XML");
            // 创建一个名为data_config的节点，因为是第一个创建，所以是根节点,再通过doc创建一个则会报错。
            Element root = doc.addElement("data_config");
            //向data_config节点中添加数据
            root.addAttribute("probe_id", probeId);
            root.addAttribute("create_time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            root.addAttribute("software_version", "6.4.108");
            root.addAttribute("hardware_version", "ND-P-1610M");
            
            // 在data_config节点下创建一个名为data_list的节点
            Element dataListShell = root.addElement("data_list");
            // 给data_list节点添加一个data_item节点
            Element dataItemShell = dataListShell.addElement("data_item");
            // 给dataItemShell节点添加一个子节点
            dataItemShell.addAttribute("task_id", taskId);
            dataItemShell.addAttribute("flag_id", "");
            dataItemShell.addAttribute("task_uuid", "");
            dataItemShell.addAttribute("type_id", "1");
            dataItemShell.addAttribute("type_name", "PING");
            //定义dataItemShell节点下的子节点及其值
            Map<String, String> shellMap=new LinkedHashMap<>();
            shellMap.put("test_time", (new Date().getTime()/1000)+"");
            shellMap.put("dns_delay", "246532");
            shellMap.put("rtt", "0");
            shellMap.put("jitter", "0");
            //生成0或100000
            shellMap.put("lost_rate", rand.nextInt(2)*100000+"");
            shellMap.put("lost_pkt_count", rand.nextInt(6)+"");
            shellMap.put("host_ip", (rand.nextInt(90)+110)+"."+(rand.nextInt(90)+110)+"."+(rand.nextInt(90)+110)+"."+(rand.nextInt(90)+110));
            //循环添加子节点和值
            for(Entry<String, String> kvp:shellMap.entrySet())
            {
                Element keyItemShell = dataItemShell.addElement(kvp.getKey());
                keyItemShell.setText(kvp.getValue());
            }
            // 用于格式化xml内容和设置头部标签
            OutputFormat format = OutputFormat.createPrettyPrint();
            // 设置xml文档的编码为utf-8
            format.setEncoding("utf-8");
            Writer out;
            // 创建一个输出流对象
            out = new FileWriter(url);
            // 创建一个dom4j创建xml的对象
            XMLWriter writer = new XMLWriter(out, format);
            // 调用write方法将doc文档写到指定路径
            writer.write(doc);
            writer.close();
            System.out.print("生成XML文件成功");
	        retBool=true;
	    }catch (Exception e) 
        {
	        e.printStackTrace();
	        System.out.print("生成XML文件失败");
	        retBool=false;
        }
	    return retBool;
	}

    
 } 
